import 'dart:io';

class DirOptions {
  bool showList;
  String indexName;

  DirOptions({required this.showList,required this.indexName});
}

class Server {
  String ip;
  int port;
  late Map<String, String> map;

  String get addr => '$ip:$port';

  Server(this.ip, this.port) : map = Map();

  void staticFiles(String src, dst) {
    map['src'] = src;
    map['dst'] = dst;
  }

  void run() async {
    print('run $addr');
    final requests = await HttpServer.bind(ip, port);
    await for (var request in requests) {
      handle(request);
    }
  }

  void handle(HttpRequest request) {
    var path = request.uri.path;
    print(path);
    var response = request.response;
    switch (request.method) {
      case 'GET':
        //主页
        if (path == '/') {
          var s = map['dst']! + 'index.html';
          print(s);
          var file = File(s);
          response..headers.contentType = ContentType.html;
          response.write(file.readAsStringSync());
        } else {
          if (path.endsWith('css')) {
            var filename =
                map['dst']! + path.substring(path.lastIndexOf('/') + 1);
            print('css $filename');
            var file = File(filename);
            response
              ..headers.contentType =
                  new ContentType("text", "css", charset: "utf-8")
              ..statusCode = HttpStatus.ok
              ..write(file.readAsStringSync());
          }
          if (path.endsWith('js')) {
            var filename = path.substring(path.lastIndexOf('/') + 1);
            var file = File(filename);
            response..headers.contentType = ContentType.text;
            response.write(file.readAsStringSync());
          }
        }
        break;
      case 'POST':
        break;
      default:
    }
    response.close();
  }
}
